# -*- coding: UTF-8 -*-
"""
HaaS506 DTU - LED Module
Function: LED activity indication
Author: HaaS506 Development Team
Version: v1.0.0
"""

from driver import GPIO
import utime
import _thread
import config  # 导入config模块以访问全局变量
# LED instances
sys_led = None
net_led = None

# Control flags
led_active = False
system_activity = False  # 保留用于其他功能

def init():
    """Initialize LED module"""
    global sys_led, net_led, led_active

    try:
        print("[LED] LED module initializing...")

        # Initialize LEDs
        sys_led = GPIO()
        sys_led.open("STATE_LED")
        sys_led.write(0)

        net_led = GPIO()
        net_led.open("NET_LED")
        net_led.write(0)

        # Start LED threads - 参考官方示例启动两个独立线程
        led_active = True
        _thread.start_new_thread(led_worker, ())
        _thread.start_new_thread(net_led_worker, ())

        print("[LED] LED module initialized with dual threads")
        return True

    except Exception as e:
        print("[LED] LED init failed: {}".format(e))
        return False

def led_worker():
    """LED控制工作线程 - 直接监听main模块全局变量"""
    while led_active:
        try:
            # 直接读取config模块的全局状态
            current_system_status = config.g_system_status
            # print("[LED] led_worker ===> current_system_status:", current_system_status)
            
            # 系统LED (system_led) - 系统状态指示
            if current_system_status == "starting":
                # 系统启动: 200ms快闪
                sys_led.write(1)
                utime.sleep_ms(200)
                sys_led.write(0)
                utime.sleep_ms(800)
            elif current_system_status == "error":
                # 系统错误: 快速闪烁
                sys_led.write(1)
                utime.sleep_ms(200)
                sys_led.write(0)
                utime.sleep_ms(200)
            elif current_system_status == "shutdown":
                # 系统关闭: 常亮
                sys_led.write(1)
                utime.sleep_ms(1000)
            else:
                # 正常运行: 心跳闪烁
                sys_led.write(1)
                utime.sleep_ms(200)
                sys_led.write(0)
                utime.sleep_ms(800)

        except Exception as e:
            print("[LED] System LED error: {}".format(e))
            utime.sleep_ms(1000)

def net_led_worker():
    """网络LED控制线程 - 直接监听main模块全局变量"""
    while led_active:
        try:
            # 直接读取config模块的全局状态
            current_network_connected = config.g_network_ready
            # print("[LED] net_led_worker ===> current_network_connected:", current_network_connected)
            current_mqtt_connected = config.g_mqtt_connected
            # print("[LED] net_led_worker ===> current_mqtt_connected:", current_mqtt_connected)
            
            # 网络LED (net_led) - 参考官方示例的精确指示
            if not current_network_connected:
                # 驻网失败/没有SIM卡/与基站脱离连接: 300ms翻转一次电平
                net_led.write(1)
                utime.sleep_ms(300)
                net_led.write(0)
                utime.sleep_ms(300)
            elif current_network_connected and not current_mqtt_connected:
                # 已驻网，未连云/与云脱离连接但还有网: 1s翻转一次
                net_led.write(1)
                utime.sleep_ms(1000)
                net_led.write(0)
                utime.sleep_ms(1000)
            elif current_network_connected and current_mqtt_connected:
                # 连着云: 常亮
                net_led.write(1)
                utime.sleep_ms(100)  # 短暂延时避免过度占用CPU
            else:
                # 未知状态: 关闭
                net_led.write(0)
                utime.sleep_ms(1000)

        except Exception as e:
            print("[LED] Network LED error: {}".format(e))
            utime.sleep_ms(1000)

# LED状态更新函数已移除 - LED线程直接监听main模块全局变量
 
def get_led_status():
    """Get current LED status information - 读取config模块全局状态"""
    return {
        "led_active": led_active,
        "system_activity": system_activity,
        "network_connected": config.g_network_ready,
        "mqtt_connected": config.g_mqtt_connected,
        "system_status": config.g_system_status
    }

def cleanup():
    """Clean up LED module"""
    global led_active, system_activity

    try:
        led_active = False
        system_activity = False

        if sys_led:
            sys_led.write(0)
            sys_led.close()

        if net_led:
            net_led.write(0)
            net_led.close()

        print("[LED] LED module cleaned up")

    except Exception as e:
        print("[LED] LED cleanup error: {}".format(e))

def shutdown():
    """Shutdown LED module"""
    cleanup()

# Legacy compatibility functions removed - use update_network_status() and update_mqtt_status() directly
